package org.example.myleet.p1405;

import java.util.PriorityQueue;

public class Solution {

    static class CharacterCount {
        private final char character;
        private int count;

        public CharacterCount(char c, int count) {
            this.character = c;
            this.count = count;
        }

        public char getCharacter() {
            return character;
        }

        public int getCount() {
            return count;
        }

        public void consume() {
            --count;
        }

        public boolean isValid() {
            return count > 0;
        }
    }

    public String longestDiverseString(int a, int b, int c) {
        int idx = 0;
        char[] charArr = new char[a + b + c];
        //贪心+优先队列，优先使用数量多的字母凑字符串，可以最小化重复3个字母的可能性
        PriorityQueue<CharacterCount> priorityQueue = new PriorityQueue<>((o1, o2) -> {
            //按照count降序排列，顶部是最大count的字母，相等时再按字母顺序排列
            if (o2.getCount() == o1.getCount()) {
                return o1.getCharacter() - o2.getCharacter();
            }
            return o2.getCount() - o1.getCount();
        });
        //依次入队各个字母的数量
        CharacterCount aCount = new CharacterCount('a', a);
        if (aCount.isValid()) {
            priorityQueue.offer(aCount);
        }
        CharacterCount bCount = new CharacterCount('b', b);
        if (bCount.isValid()) {
            priorityQueue.offer(bCount);
        }
        CharacterCount cCount = new CharacterCount('c', c);
        if (cCount.isValid()) {
            priorityQueue.offer(cCount);
        }
        while (!priorityQueue.isEmpty()) {
            //循环直到消耗完所有字母为止
            //取出堆顶最多的字母
            CharacterCount charCount = priorityQueue.poll();
            if (idx > 1) {
                if (charArr[idx - 2] == charArr[idx - 1] && charArr[idx - 1] == charCount.getCharacter()) {
                    //发现前2个字母相同并且当前堆顶字母和前2个字母相同
                    if (priorityQueue.isEmpty()) {
                        //没有其他字母了，退出
                        break;
                    }
                    //还有数量第二多的字母，用这个来继续凑
                    CharacterCount charCount2 = priorityQueue.poll();
                    charArr[idx++] = charCount2.getCharacter();
                    charCount2.consume();
                    if (charCount2.isValid()) {
                        priorityQueue.offer(charCount2);
                    }
                }
            }
            //每次凑一个字母
            charArr[idx++] = charCount.getCharacter();
            charCount.consume();
            if (charCount.isValid()) {
                priorityQueue.offer(charCount);
            }
        }
        char[] result = new char[idx];
        System.arraycopy(charArr, 0, result, 0, idx);
        //返回快乐字符串
        return new String(result);
    }
}
